package com.kkk.shop.head.controller;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kkk.shop.common.controller.BaseController;
import com.kkk.shop.common.util.ConstantFinalUtil;
import com.kkk.shop.common.util.PageInfoUtil;
import com.kkk.shop.goods.pojo.AGoods;
import com.kkk.shop.goods.pojo.AGoodsEnum;
import com.kkk.shop.goods.service.IGoodsService;
import com.kkk.shop.user.pojo.AUsers;
import com.kkk.shop.user.pojo.AUsersCar;
import com.kkk.shop.user.service.IUserService;

/**
 * 不需要登陆就可以访问的页面
 * @author kkk
 *
 */
@Controller
public class GoodsHeadController extends BaseController
{
	@Resource
	private IGoodsService goodsService;
	@Resource
	private IUserService userService;
	/**
	 * 商品列表页面
	 * @return
	 */
	@RequestMapping("/goods")
	public String goodsList(HttpServletRequest request)
	{
		ConstantFinalUtil.loggerMsg.info("---goodsList--request--");
		return this.goodsList(request,"1");
	}
	
	/**
	 * 商品列表页面
	 * @return
	 */
	@RequestMapping("/goods_{currentPage}")
	public String goodsList(HttpServletRequest request,@PathVariable String currentPage)
	{
		ConstantFinalUtil.loggerMsg.info("---goodsList--request--currentPage--");
		PageInfoUtil pageInfoUtil = this.proccedPageInfo(currentPage,ConstantFinalUtil.BUNDLE.getString("head.pageSize.image"));
		
		/* 按照条件查询数据 */
		Map<String, Object> paramMap =  this.getParamMap();
		paramMap.put("status", AGoodsEnum.STATUS_ENABLE.getStatus());
		/* 查询数据 */
		List<AGoods> goodsList = this.goodsService.queryMultiGoodsService(pageInfoUtil, paramMap);
		/* 存储结果 */
		request.setAttribute("goodsList", goodsList);
		request.setAttribute("pageInfoUtil", pageInfoUtil);
		request.setAttribute("websitePath", ConstantFinalUtil.BUNDLE.getString("website.path"));
		return "/head/goodsList" ; 
	}
	
	/**
	 * 商品详情
	 * @return
	 */
	@RequestMapping("/goods/{gid}")
	public String goodsInfo(HttpServletRequest request , @PathVariable String gid)
	{
		ConstantFinalUtil.loggerMsg.info("---- goodsInfo ----");
		/* 根据Id查询商品详情 */
		Map<String, Object> paramMap = this.getParamMap();
		paramMap.put("id", gid);
		AGoods goods = this.goodsService.queryOneGoodsService(paramMap);
		/* 存储request */
		request.setAttribute("goods", goods);
		return "/head/goodsInfo" ; 
	}
	
	/**
	 * 购物车列表
	 * [
	 * 	{'id':'12','num':'5'},
	 * 	{'id':'1','num':'2'}
	 * ]
	 * @param request
	 * @return
	 * */
	@RequestMapping("/shopCarList")
	public String shopCarList(HttpServletRequest request)
	{
		ConstantFinalUtil.loggerMsg.info("-------shopCarList---------");
		//判断是否登录
		HttpSession session=request.getSession();
		AUsers users=(AUsers) session.getAttribute("users");
		
		JSONArray shopCarArr=new JSONArray();
		Map<String,Object> paramMap=this.getParamMap();
		if(users!=null)
		{
			//用户已经登录,去查询购物车
			paramMap.put("usersId",users.getId());
			List<AUsersCar> usersCarList=this.userService.queryMultiAUsersCarService(null, paramMap);
			for(Iterator it=usersCarList.iterator();it.hasNext();)
			{
				AUsersCar usersCar=(AUsersCar) it.next();
				AGoods goods=usersCar.getGoods();
				JSONObject json=new JSONObject();
				json.put("id", usersCar.getId());
				json.put("name", goods.getName());
				json.put("price", goods.getPrice() + "");
				json.put("remainNumStr", goods.getRemainNumStr());
				json.put("img", goods.getListImgPath());
				json.put("num", usersCar.getNum());
				shopCarArr.add(json);
			}
		}else
		{
			//从cookie中查询购物车信息
			shopCarArr=shopCarListCookie(request);
		}
		//接收gid,表示新增加的商品
		String gid=request.getParameter("gid");
		if(gid==null)
		{
			gid="";
		}
		if(!"".equalsIgnoreCase(gid))
		{
			//根据id查询商品
			paramMap.clear();
			paramMap.put("id",gid);
			AGoods goods=this.goodsService.queryOneGoodsService(paramMap);
			request.setAttribute("goods",goods);
		}
		//存储结果
		request.setAttribute("shopCarArr",shopCarArr);
		request.setAttribute("websitePath",ConstantFinalUtil.BUNDLE.getString("website.path"));
		return "/head/shopCarList";
	}
	/**
	 * 未登录,取cookie的购物车
	 * @param request
	 * @return
	 * */
	private JSONArray shopCarListCookie(HttpServletRequest request)
	{
		String shopCarListStr="[]";
		//从cookie中取数据
		Cookie[] cookies=request.getCookies();
		if(cookies!=null)
		{
			for(int i=0;i<cookies.length;i++)
			{
				Cookie cookieTemp=cookies[i];
				if("shopCarList".equalsIgnoreCase(cookieTemp.getName()))
				{
					//取出购物车的json数据
					shopCarListStr=cookieTemp.getValue();
					break;
				}
			}
		}
		
		//将cookie的数据转换成JSON对象
		JSONArray shopCarArr=JSON.parseArray(shopCarListStr);
		Map<String,Object> paramMap=this.getParamMap();
		for(Iterator it=shopCarArr.iterator();it.hasNext();)
		{
			JSONObject json=(JSONObject) it.next();
			String gid=json.getString("id");
			String num=json.getString("num");
			
			//根据id查询商品
			paramMap.clear();
			paramMap.put("id",gid);
			AGoods goods=this.goodsService.queryOneGoodsService(paramMap);
			json.put("id","0");
			json.put("name",goods.getName());
			json.put("price",goods.getPrice());
			//库存量
			json.put("remainNumStr",goods.getRemainNumStr());
			json.put("img",goods.getListImgPath());
			//是不是要调用shopCarArr.add(json)???
		}
		return shopCarArr;
	}
	
	/**
	 * 加入购物车
	 * @param request
	 * @param response
	 * @param gid
	 * @return String
	 * @throws InterruptedException 
	 * */
	@RequestMapping("shopCarInsertSubmit")
	public String shopCarInsertSubmit(HttpServletRequest request,HttpServletResponse response,String gid) throws InterruptedException
	{
		ConstantFinalUtil.loggerMsg.info("------shopCarInsertSubmit------");
		//判断是否登录
		HttpSession session=request.getSession();
		AUsers users=(AUsers) session.getAttribute("users");
		Map<String,Object> paramMap=this.getParamMap();
		if(users!=null)
		{
			String numStr=request.getParameter("num");
			if(numStr==null)
			{
				numStr="";
			}
			if("".equalsIgnoreCase(numStr))
			{
				numStr="1";
			}
			//已经登录,直接将购物车信息插入数据库中
			paramMap.clear();
			paramMap.put("usersId",users.getId());
			paramMap.put("goodsId",gid);
			AUsersCar usersCar=this.userService.queryOneAUsersCarService(paramMap);
			
			boolean flag=false;
			if(usersCar==null)
			{
				usersCar = new AUsersCar();
				usersCar.setGoodsId(Integer.valueOf(gid));
				usersCar.setUsersId(users.getId());
				usersCar.setNum(Integer.valueOf(numStr));
				usersCar.setStatus(Byte.valueOf("1"));
				usersCar.setCreateTime(new Date());
				flag = false ; 
			}else
			{
				//同一个用户如果已经存在,则进行更新购物车里面的数量=旧的+新的
				usersCar.setNum(usersCar.getNum()+Integer.valueOf(numStr));
			}
			usersCar.setPubTime(new Date());
			usersCar.setUpdateTime(new Date());
			//如果已经登录,则更新;否则,插入
			if(flag)
			{
				this.userService.updateOneAUsersCarService(usersCar);
			}else
			{
				this.userService.insertOneAUsersCarService(usersCar);
			}
		}else
		{
			//未登录,操作Cookie
			shopCarInsertCookie(request,response,gid);
		}
		return "redirect:/shopCarList.html?gid="+gid;
	}
	
	/**
	 * 未登录,添加购物车,操作cookie
	 * @param request
	 * @param response
	 * @param gid
	 * @return 
	 * @throws InterruptedException 
	 * */
	private void shopCarInsertCookie(HttpServletRequest request,HttpServletResponse response,String gid) throws InterruptedException
	{
		//商品数量
		String numStr=request.getParameter("num");
		if(numStr==null)
		{
			numStr="";
		}
		if("".equalsIgnoreCase(numStr))
		{
			numStr="1";
		}
		String shopCarListStr="[]";
		Cookie[] cookies=request.getCookies();
		if(cookies!=null)
		{
			for(int i=0;i<cookies.length;i++)
			{
				Cookie cookieTemp=cookies[i];
				if("shopCarList".equalsIgnoreCase(cookieTemp.getName()))
				{
					//存储购物车的json数据
					shopCarListStr=cookieTemp.getValue();
					break;
				}
			}
		}
		//将拼接好的字符串,转成jsonArray数组
		JSONArray shopCarArr=JSON.parseArray(shopCarListStr);
		/* 将商品id和数量添加到json中,
		 * 循环json,判断商品是否存在
		 *  */
		JSONObject goodsJSON=new JSONObject();
		boolean flag=false;
		for(Iterator it=shopCarArr.iterator();it.hasNext();)
		{
			JSONObject json=(JSONObject) it.next();
			if(gid.equalsIgnoreCase(json.getString("id")))
			{
				//数量=旧的+新的
				int num=Integer.valueOf(json.getString("num"))+Integer.valueOf(numStr);
				json.put("num",num+"");
				flag=true;
				break;
			}
		}
		//找不到商品id时,则新增的商品,添加到购物车的json中
		if(!flag)
		{
			goodsJSON.put("id", gid);
			goodsJSON.put("num", numStr);
			shopCarArr.add(goodsJSON);
		}
		/* 将json存储Cookie中 */
		Cookie cookie = new Cookie("shopCarList", shopCarArr.toJSONString());
		cookie.setPath(request.getContextPath());
		cookie.setMaxAge(-1);
		response.addCookie(cookie);
		Thread.sleep(50);
	}
}
